package com.pp.web.controller;

import com.pp.common.pojo.Comment;
import com.pp.common.pojo.User;
import com.pp.common.vo.SysResult;
import com.pp.web.model.dto.CreateCommentDTO;
import com.pp.web.model.vo.CommentVO;
import com.pp.web.service.ICommentService;
import com.pp.web.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.List;

import static com.pp.common.util.JwtUtils.USERNAME;

@RestController
@RequestMapping("/api/comment")
public class CommentController {

    @Resource
    private IUserService userService;

    @Resource
    private ICommentService commentService;

    /**
     * 根据 postId 获取对应的所有 comments
     * 请求方法: GET
     * 请求URL: http://localhost:8090/api/comment/list
     * 请求参数: postId
     * 返回值: SysResult(comments)
     */
    @GetMapping("/list")
    public SysResult getCommentsByPostId(
        @RequestParam(value = "postId", defaultValue = "1") String postId) {
        List<CommentVO> comments = commentService.getCommentsByPostId(postId);
        return SysResult.success(comments);
    }

    /**
     * 添加评论
     * 请求方法: POST
     * 请求URL: http://localhost:8090/api/comment/create
     * 请求参数: commentDTO
     * 返回值: SysResult(comment)
     */
    @PostMapping("/create")
    public SysResult createComment(
        @RequestHeader(value = USERNAME) String username,
        @RequestBody CreateCommentDTO createCommentDTO) {
        User user = userService.getUserByUsername(username);
        Comment comment = commentService.createComment(createCommentDTO, user);
        return SysResult.success(comment);
    }

}

